﻿using System.Activities;
using log4net;

namespace Reactor.Workflow.Activities
{
    public class ReceiveMessage<T> : NativeActivity<T>
    {
        protected ILog Log;

        /// <summary>
        /// Initializes a new instance of the <see cref="ReceiveMessage&lt;T&gt;"/> class.
        /// </summary>
        public ReceiveMessage()
        {
            Log = LogManager.GetLogger(GetType());
        }

        [RequiredArgument]
        public InArgument<string> BookmarkName { get; set; }

        #region Overrides of NativeActivity<T>

        /// <summary>
        /// When implemented in a derived class, runs the activity’s execution logic.
        /// </summary>
        /// <param name="context">The execution context in which the activity executes.</param>
        protected override void Execute(NativeActivityContext context)
        {
            var bookmarkName = context.GetValue(BookmarkName);

            if (Log.IsDebugEnabled) Log.DebugFormat("Creating workflow bookmark: {0}", bookmarkName);

            context.CreateBookmark(bookmarkName, OnResumeBookmark);
        }

        protected override bool CanInduceIdle
        {
            get { return true; }
        }

        #endregion

        protected virtual void OnResumeBookmark(NativeActivityContext context, Bookmark bookmark, object obj)
        {
            if (Log.IsDebugEnabled) Log.DebugFormat("Resuming workflow bookmark: {0}", bookmark.Name);

            Result.Set(context, (T)obj);
        }
    }
}
